<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="模型" prop="categoryId">
                <el-select
                    v-model="queryParams.categoryId"
                    placeholder="请选择模型"
                    clearable
                    @change="handleQuery"
                >
                    <el-option
                        v-for="model in modelOptions"
                        :key="model.id"
                        :label="model.name"
                        :value="model.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="Plus"
                    @click="handleAdd"
                    v-hasPermi="['questions:questions:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="Edit"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['questions:questions:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="Delete"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['questions:questions:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="Download"
                    @click="handleExport"
                    v-hasPermi="['questions:questions:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="questionsList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="id" align="center" prop="id" />
            <el-table-column label="问题" align="center">
                <template #default="scope">
                    <div v-html="renderMarkdown(scope.row.content)" />
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="修改时间" align="center" prop="updatedAt" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="模型" align="center">
                <template #default="scope">
                    <span>{{ getModelName(scope.row.categoryId) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['questions:questions:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['questions:questions:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 修改后的对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="questionsRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="问题">
                    <editor :key="editorKey" v-model="form.content" :min-height="192" />
                </el-form-item>
                <el-form-item label="模型" prop="categoryId">
                    <el-select
                        v-model="form.categoryId"
                        placeholder="请选择模型"
                        clearable
                        filterable
                    >
                        <el-option
                            v-for="model in modelOptions"
                            :key="model.id"
                            :label="model.name"
                            :value="model.id"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Questions">
import { getCurrentInstance, ref, reactive, toRefs, onMounted } from 'vue'
import { listQuestions, getQuestions, delQuestions, addQuestions, updateQuestions } from "@/api/questions/questions";
import { listModels } from "@/api/models/models"; // 假设存在获取模型列表的 API
import { marked } from 'marked'
import DOMPurify from 'dompurify'

const { proxy } = getCurrentInstance();

const questionsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const editorKey = ref(0);
const modelOptions = ref([]);
const modelMap = ref({});

const data = reactive({
    form: {
        id: null,
        content: null,
        createdAt: null,
        updatedAt: null,
        categoryId: null
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null,
        categoryId: null
    },
    rules: {
        content: [
            { required: true, message: "问题不能为空", trigger: "blur" }
        ],
        categoryId: [
            { required: true, message: "模型不能为空", trigger: "change" }
        ]
    }
});

const { queryParams, form, rules } = toRefs(data);

// 获取模型列表
const getModelList = async () => {
    try {
        const response = await listModels();
        modelOptions.value = response.rows;
        modelMap.value = response.rows.reduce((acc, model) => {
            acc[model.id] = model.name;
            return acc;
        }, {});
    } catch (error) {
        console.error('获取模型列表失败:', error);
    }
};

// 根据 categoryId 获取模型名称
const getModelName = (categoryId) => {
    return modelMap.value[categoryId] || '未知模型';
};

/** 查询问题管理列表 */
const getList = async () => {
    loading.value = true;
    try {
        const response = await listQuestions(queryParams.value);
        questionsList.value = response.rows;
        total.value = response.total;
    } catch (error) {
        console.error('获取问题列表失败:', error);
    } finally {
        loading.value = false;
    }
};

// 取消按钮
const cancel = () => {
    open.value = false;
    reset();
};

// 表单重置
const reset = () => {
    form.value = {
        id: null,
        content: null,
        createdAt: null,
        updatedAt: null,
        categoryId: null
    };
    if (proxy.$refs.questionsRef) {
        proxy.$refs.questionsRef.clearValidate();
        proxy.$refs.questionsRef.resetFields();
    }
    editorKey.value++;
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
    proxy.resetForm("queryRef");
    queryParams.value.categoryId = null;
    handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length!== 1;
    multiple.value =!selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    open.value = true;
    title.value = "添加问题管理";
};

/** 修改按钮操作 */
const handleUpdate = async (row) => {
    reset();
    const _id = row.id || ids.value;
    try {
        const response = await getQuestions(_id);
        form.value = response.data;
        // 设置表单的 categoryId 为模型名称
        form.value.categoryId = getModelName(form.value.categoryId);
        open.value = true;
        title.value = "修改问题管理";
    } catch (error) {
        console.error('获取问题详情失败:', error);
    }
};

/** 提交按钮 */
const submitForm = () => {
    proxy.$refs["questionsRef"].validate(valid => {
        if (valid) {
            // 将模型名称转换回 categoryId
            const selectedModel = modelOptions.value.find(model => model.name === form.value.categoryId);
            if (selectedModel) {
                form.value.categoryId = selectedModel.id;
            }

            if (form.value.id!== null) {
                updateQuestions(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addQuestions(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
};

/** 删除按钮操作 */
const handleDelete = (row) => {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除问题管理编号为"' + _ids + '"的数据项？').then(() => {
        return delQuestions(_ids);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
};

/** 导出按钮操作 */
const handleExport = () => {
    proxy.download('questions/questions/export', {
        ...queryParams.value
    }, `questions_${new Date().getTime()}.xlsx`)
};

// 渲染 Markdown 内容
const renderMarkdown = (content) => {
    return DOMPurify.sanitize(marked.parse(content || ''))
};

// 时间解析函数（需要根据实际情况实现）
const parseTime = (time, format) => {
    if (!time) return ''
    // 这里简单返回时间字符串，实际需要实现具体的时间解析逻辑
    return new Date(time).toLocaleString()
};

onMounted(async () => {
    await getModelList();
    getList();
});
</script>

<style scoped>
.app-container {
    padding: 20px;
}
.el-select {
    width: 100%;
}
</style>